<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'material:arrival:pmPuArrivalvouch:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmPUArrivalVouchsList>
        <BasicTable
          @register="registerPmPUArrivalVouchsTable"
          @row-click="handlePmPUArrivalVouchsRowClick"
        />
        <a-button class="mt-2 mr-2" v-if="(status == '9'|| status == '6'|| !status) ?true:false" @click="handlePmPUArrivalVouchsAdd" v-auth="'material:arrival:pmPuArrivalvouch:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>

        <a-button
          v-if="(status == '9'|| status == '6'|| !status) ?true:false"
          class="mt-2 mr-2"
          @click="openModal(true, {})"
          v-auth="'material:arrival:pmPuArrivalvouch:edit'"
        >
          <Icon icon="simple-line-icons:calendar" /> {{ t('批量修改需求日期') }}
        </a-button>
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmArrivalVouch"
        completeText="提交"
        :loading="loadingRef"
        :auth="'material:arrival:pmPuArrivalvouch:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="shxqListSelect"
      v-show="false"
      selectType="materialarrivalSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />

  <Modal @register="register" @modifyneedDate="modifyneedDate" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMaterialArrivalPmPuArrivalvouchForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PmPuArrivalvouch, pmPuArrivalvouchSave, pmPuArrivalvouchForm } from '/@/api/material/arrival/pmPuArrivalvouch';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';
  import { useModal } from '/@/components/Modal';
  import Modal from './Modal.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('material.arrival.pmPuArrivalvouch');
  const { showMessage } = useMessage();
  const record = ref<PmPuArrivalvouch>({} as PmPuArrivalvouch);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增送货需求') : t('编辑送货需求'),
  }));

  const loadingRef = ref(false);
  let status = ref<any>('');
    let listSelectRef = ref([]);
  let queryParams = ref({});
  let shxqListSelect = ref<any>('');

  const inputFormSchemas: FormSchema[] = [
     {
      label: t('申请信息'),
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('需求单号'),
      field: 'djno',
      component: 'Input',
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        // valueFormat: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      // required: true,
    },

   
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            projectno: e,
          };
          let arr = await pmPUArrivalVouchsTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            await pmPUArrivalVouchsTable.deleteTableDataRecord(item);
          });
        },
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
      dynamicDisabled: computed(() => (status.value == '9'|| status.value == '6'|| !status.value) ?false:true),
    },
    {
      label: t('项目编码'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      dynamicDisabled: true,
      required: true,
    },
    
    // {
    //   label: t('项目编码'),
    //   field: 'projectno',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   required: true,
    // },
    // {
    //   label: t('项目名称'),
    //   field: 'projectname',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   required: true,
    // },
    {
      label: t('需求说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
      dynamicDisabled: computed(() => (status.value == '9' || status.value == '6' ||!status.value) ?false:true),

    },
    {
      label: t('发起人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
      ifShow:computed(() => !record.value.isNewRecord),
    },
    {
      label: t('发起时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      ifShow:computed(() => !record.value.isNewRecord),
    },
    {
      label: t('需求明细'),
      field: 'clzjx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      // label: t('库领申请子表'),
      field: 'pmPUArrivalVouchsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmPUArrivalVouchsList',
    },
    // {
    //   label: t('确认信息'),
    //   field: 'qrxx',
    //   component: 'FormGroup',
    //   colProps: { lg: 24, md: 24 },
    //   ifShow:computed(() => !record.value.isNewRecord),
    // },
    // {
    //   label: t('送货单号'),
    //   field: 'djno',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   dynamicDisabled: true,
    //   ifShow:computed(() => !record.value.isNewRecord),
    // },
    
  ];

  const [register, { openModal }] = useModal();
  

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmPUArrivalVouchsTable, pmPUArrivalVouchsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmPUArrivalVouchsDelete.bind(this, record),
          },
          auth: 'material:arrival:pmPuArrivalvouch:edit',
          ifShow: () => status.value == '9'|| status.value == '6'||!status.value ?true:false,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmPUArrivalVouchsTableData(_res: Recordable) {
    pmPUArrivalVouchsTable.setColumns([
     

      // {
      //   title: t('订单ID'),
      //   dataIndex: 'poid',
      //   width: 130,
      //   align: 'left',
      // },
      // {
      //   title: t('订单子表ID'),
      //   dataIndex: 'podid',
      //   width: 130,
      //   align: 'left',
        
      // },


      {
        title: t('材料编码'),
        dataIndex: 'mcode',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: true,
      },
      {
        title: t('材料名称'),
        dataIndex: 'basInv.mname',
        width: 150,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: true,
      },
      {
        title: t('规格型号'),
        dataIndex: 'basInv.mstd',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: false,
      },
      {
        title: t('订单号'),
        dataIndex: 'cpoid',
        width: 130,
        align: 'left',
      },
      {
        title: t('订单日期'),
        dataIndex: 'dpodate',
        width: 100,
        align: 'left',
      },
      {
        title: t('行号'),
        dataIndex: 'rowno',
        width: 60,
        align: 'center',
      },
     
      {
        title: t('单位'),
        dataIndex: 'basInv.unit',
        width: 80,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        // editRule: true,
      },
      {
        title: t('剩余数量'),
        dataIndex: 'syQty',
        width: 100,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 16,
        // },
        // editRule: true,
      },
      {
        title: t('需求数量'),
        dataIndex: 'iqty',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
     
      {
        title: t('需求日期'),
        dataIndex: 'needDate',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: true,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('供应商'),
        dataIndex: 'venName',
        width: 120,
        align: 'left',
      },
    ]);
    pmPUArrivalVouchsTable.setTableData(record.value.childList || []);
  }

  function handlePmPUArrivalVouchsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmPUArrivalVouchsAdd() {
    // pmPUArrivalVouchsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    if (!getFieldsValue().projectno) {
      showMessage('请先选择项目名称！');
      return;
    }
    listSelectRef.value = [];
    let arr = pmPUArrivalVouchsTable.getDataSource().map((item) => {
      return item.mcode;
    });
    queryParams.value.selIds = arr.join(',')
    shxqListSelect.value.handleInputClick()
  }

  async function modifyneedDate(data) {
    for (const record of pmPUArrivalVouchsTable.getDataSource()) {
      record.needDate = data.needDate;
      // console.log(data,'record');
    }
  }

  async function handSelect(selectData) {
    let arr = await pmPUArrivalVouchsTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.podid == item.podid) {
          flag = false;
        }
      });
      if (flag) {
        pmPUArrivalVouchsTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          projectno:item.pcode,
          basInv:{
            unit:item.unit,
            mstd:item.mstd,
            mname:item.mname,
          },
          syQty:item.syQty || 0,
          iqty:item.syQty,
        });
      }
    });
  }

  function handlePmPUArrivalVouchsDelete(record: Recordable) {
    pmPUArrivalVouchsTable.deleteTableDataRecord(record);
  }

  async function getPmPUArrivalVouchsList() {
    let pmPUArrivalVouchsListValid = true;
    let pmPUArrivalVouchsList: Recordable[] = [];
    for (const record of pmPUArrivalVouchsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmPUArrivalVouchsListValid = false;
      }
      pmPUArrivalVouchsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmPUArrivalVouchsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmPUArrivalVouchsList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmPUArrivalVouchsListValid) {
      throw { errorFields: [{ name: ['pmPUArrivalVouchsList'] }] };
    }
    return pmPUArrivalVouchsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmPuArrivalvouchForm(data);
    record.value = (res.pmPuArrivalvouch || {}) as PmPuArrivalvouch;
    record.value.__t = new Date().getTime();
    status.value = record.value.status
    queryParams.value = {
      projectno: record.value.projectno,
    };
    setFieldsValue(record.value);
    setPmPUArrivalVouchsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.childList = await getPmPUArrivalVouchsList();
      let flag = true
      
      data.childList.forEach(item=>{
        if(item.iqty > item.syQty && item.status != "1"){
          flag = false
        }
      })
      if(!flag){
        showMessage('需求数量不能大于剩余数量！');
        return false;
      }


      // console.log('submit', params, data, record);
      const res = await pmPuArrivalvouchSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
